import React, { useState, useEffect, createContext } from "react";
import "antd/dist/antd.css";
import { Card, Input, Button, Spin, message } from "antd";
import '../common/login.css'
import { UserOutlined, KeyOutlined } from '@ant-design/icons'
import servicePath from '../config/apiUrl'
import axios from 'axios'

const openIdContext = createContext()

const Login = (props) => {
  const [userName, setUserName] = useState("");
  const [password, setPassword] = useState("");
  const [isLoading, setLoading] = useState(false);

  useEffect(() => {

  }, [])

  // 登录方法
  const checkLogin = () => {
    setLoading(true)

    if (!userName) return message.error('用户名不能为空')
    else if (!password) return message.error('密码不能为空')
    
    let params = {
      userName,
      password
    }

    axios({
      method: 'post',
      url: servicePath.checkLogin,
      data: params,
      withCredentials: true
    }).then(
      (res) => {
        setLoading(false)
        if (res.data.data == '登录成功') {
          localStorage.setItem('openId', res.data.openId)
          props.history.push('/index')
        } else {
          message.error('用户名或密码错误')
        }
      }
    )

    setTimeout(() => {
      setLoading(false)
    }, 1000);
  }

  return (
    <div className="login-div">
      <Spin tip="Loading..." spinning={isLoading}>
        <Card title="技术派" bordered={true} style={{ width: 400 }}>
          <Input
            id="userName"
            size="large"
            placeholder="Enter your userName"
            prefix={<UserOutlined style={{ color: "rgba(0,0,0,.25)" }} />}
            onChange={(e) => {
              setUserName(e.target.value);
            }}
          />
          <br/><br/>
          <Input.Password id="password" size="large" placeholder="Enter your password" onChange={(e) => { setPassword(e.target.value)}} prefix={<KeyOutlined style={{color: 'rgba(0,0,0,.25)'}} />} />
          <br/><br/>
          <Button type="primary" size="large" block onClick={checkLogin}> Login in </Button>
        </Card>
      </Spin>
    </div>
  );
};

export default Login;
